package com.qidian.permission.service.impl;

import com.qidian.permission.entity.Permission;
import com.qidian.permission.mapper.PermissionMapper;
import com.qidian.permission.service.PermissionService;
import com.qidian.permission.util.PerResult;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @Author 32郗建狄
 * @Company GX631
 * Time 2023/10/18 21:02
 * Description
 */
@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    PermissionMapper permissionMapper;
    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public PerResult selectAll() {
        // 先查询1级别类目  这里调用了一个递归查询的方法
        // 获取PermissionServiceImpl的代理对象
        PermissionService permissionService = (PermissionService) AopContext.currentProxy();
        List<Permission> permissions = permissionService.selectByParentId(0L);
        return PerResult.ok(permissions);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Permission> selectByParentId(Long parentId) {
        PermissionService permissionService = (PermissionService) AopContext.currentProxy();
        List<Permission> permissions = permissionMapper.selectByParentId(parentId);
        for (Permission p:permissions) {
            if (p.getParent().equals(new Integer(2))){    // 有子权限，递归查询
                p.setChildren(permissionService.selectByParentId(p.getPermissionId()));
            }
        }
        return permissions;
    }

    @Override
    public PerResult queryByUserId(Long userId) {
        if (Objects.nonNull(userId)){
            return PerResult.ok(permissionMapper.queryByUserId(userId));
        }
        return PerResult.fail();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public PerResult settingUserPermission(Long userId, Long[] permissionIds) {
        if (Objects.isNull(permissionIds)){
            permissionMapper.deleteRelationByUserId(userId);
            return PerResult.ok();
        }
        permissionMapper.deleteRelationByUserId(userId);    //先删除之前拥有的权限
        permissionMapper.insertUserPermissionRelation(userId,permissionIds);    //在设置更改的权限
        return PerResult.ok();
    }


}
